package com.timmy.progressview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * Created by Timmy on 2016/12/15.
 */

public class ProgressView extends LinearLayout {

    private ImageView mIvIcon;
    private TextView  mTv;
    private Paint     mPaint;

    private long progress;
    private long    max              = 100;
    private boolean isProgressEnable = true;
    private RectF mOval;

    /**
     * 设置进度的返回值
     */
    public void setProgress(long progress) {
        this.progress = progress;

        invalidate();
    }

    /**
     * 设置进度的最大值
     */
    public void setMax(long max) {
        this.max = max;
    }


    /**
     * 设置是否允许进度
     */
    public void setProgressEnable(boolean progressEnable) {
        isProgressEnable = progressEnable;
    }

    public ProgressView(Context context) {
        this(context, null);
    }

    /**
     * 设置图标
     */
    public void setIcon(int id) {

        mIvIcon.setImageResource(id);
    }

    /**
     * 设置文本
     */
    public void setNote(String note) {
        mTv.setText(note);
    }

    public ProgressView(Context context, AttributeSet attrs) {
        super(context, attrs);

        //转载布局
        View view = View.inflate(context, R.layout.inflate_progressview, this);

        //找到孩子
        mIvIcon = (ImageView) view.findViewById(R.id.progressview_iv);
        mTv = (TextView) view.findViewById(R.id.progressview_tv);
    }

    @Override
    protected void onDraw(Canvas canvas) {


        super.onDraw(canvas);

    }

    @Override
    protected void dispatchDraw(Canvas canvas) {

        super.dispatchDraw(canvas);

        if (isProgressEnable) {

            int left   = mIvIcon.getLeft();
            int top    = mIvIcon.getTop();
            int right  = mIvIcon.getRight();
            int bottom = mIvIcon.getBottom();

            if (mOval == null) {
                mOval = new RectF(left, top, right, bottom);
            }

            float   startAngle = -90; //初始角度
            float   sweepAngle = (progress * 1.0f / max) * 360;       //动态计算扫过的角度
            boolean useCenter  = false;

            if (mPaint == null) {
                mPaint = new Paint();

                //设置笔的属性
                mPaint.setStyle(Paint.Style.STROKE);
                mPaint.setColor(Color.BLUE);
                mPaint.setStrokeWidth(3);
                mPaint.setAntiAlias(true);
            }

            canvas.drawArc(mOval, startAngle, sweepAngle, useCenter, mPaint);
        }
    }
}
